package com.bytenebula.asteroid.service.impl;

import com.bytenebula.ByteNebulaException;
import com.bytenebula.ResultCodes;
import com.bytenebula.entity.meta.MetaColumn;
import com.bytenebula.asteroid.service.MetaColumnService;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.bytenebula.entity.meta.MetaTable;
import com.bytenebula.asteroid.mapper.MetaTableMapper;
import com.bytenebula.asteroid.service.MetaTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *  服务层实现。
 *
 * @author patrick
 * @since 2024-09-15
 */
@Service
public class MetaTableServiceImpl
        extends ServiceImpl<MetaTableMapper, MetaTable>
        implements MetaTableService {


    @Autowired
    private MetaColumnService columnService;

    /**
     * 新建MetaTable，并同时新建内部MetaColumn
     *
     * @param table
     * @return 创建成功返回id，否则返回Null
     */
    @Override
    public Integer saveWithColumns(MetaTable table) {
        try {
            return Db.txWithResult(() -> {
                try {
                    if (!super.save(table))
                        throw new ByteNebulaException(ResultCodes.DB_OPERATION_FAILED);
                    for (MetaColumn col : table.getColumns()) {
                        col.setId(null);
                        col.setTableId(table.getId());
                        col.setTenantId(table.getTenantId());
                        if (!columnService.save(col))
                            throw new ByteNebulaException(ResultCodes.DB_OPERATION_FAILED);
                    }
                    return table.getId();
                } catch (Exception e) {
                    throw new ByteNebulaException(ResultCodes.DB_OPERATION_FAILED);
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据id获取MetaTable对象，并获取字段列表
     *
     * @param id
     * @return 如果id存在返回MetaTable对象，否则返回NULL
     */
    @Override
    public MetaTable getOneWithRelationsById(Integer id) {
        return mapper.selectOneWithRelationsById(id);
    }
}
